import initCalendar, {
  getSelectedDay,
  setTodoLabels,
  disableDay
} from '../../template/calendar/index';
var api = require("../../mars/services/api.js");
let wxCharts = require("../../mars/plugins/charts.uncomp.js");
let that;
var app = getApp();
import chartWrap from '../canvas/chartWrap'
import getConfig from '../../mars/plugins/getLineconfig.js'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    animationFoot: {},
    isshow: false,
    animation: {},
    myCanvasStyle: {
      width: "",
      height: "",
    },
    userInfo: {
      id: "",
      user_name: "",
      avatar_url: ""
    },
    punchTimes: 0,
    punchRecords: [],
    currentDateSelect: "",
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    let avatarUrl = options.avatarUrl;
    let userName = options.userName;
    let userId = options.userId;

    let curDate = new Date();

    let year = curDate.getFullYear();
    let month = curDate.getMonth() + 1 + '';
    month = month.padStart(2, '0');
    let date = curDate.getDate() + '';
    date = date.padStart(2, '0');
    that.setData({
      userInfo: {
        id: userId,
        user_name: userName,
        avatar_url: avatarUrl
      },
      currentDateSelect: year + '-' + month + '-' + date
    });

    that.getPunchTimeByUserId(userId);
    that.getPunchRecordByDay(that.data.currentDateSelect, userId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    initCalendar({
      multi: false, // 是否开启多选,
      // disablePastDay: true, // 是否禁选过去日期
      // defaultDay: '2018-8-8', // 初始化日历时指定默认选中日期，如：'2018-3-6' 或 '2018-03-06'
      /**
       * 选择日期后执行的事件
       * @param { object } currentSelect 当前点击的日期
       * @param { array } allSelectedDays 选择的所有日期（当mulit为true时，才有allSelectedDays参数）
       */
      afterTapDay: (currentSelect, allSelectedDays) => {
        console.log('===============================');
        console.log('当前点击的日期', currentSelect);
        console.log('当前点击的日期是否有事件标记: ', currentSelect.hasTodo || false);
        allSelectedDays && console.log('选择的所有日期', allSelectedDays);
        console.log('getSelectedDay方法', getSelectedDay());

        let month = currentSelect.month + '';
        let day = currentSelect.day + '';
        let dayStr = currentSelect.year + '-' + month.padStart(2, '0') + '-' + day.padStart(2, '0');
        that.setData({
          currentDateSelect: dayStr
        })
        that.getPunchRecordByDay(dayStr, that.data.userInfo.id);
      },
      whenChangeMonth(current, next) {
        // console.log(current);
        // console.log(next);
      },
      /**
       * 日期点击事件（此事件会完全接管点击事件）
       * @param { object } currentSelect 当前点击的日期
       * @param { object } event 日期点击事件对象
       */
      // onTapDay(currentSelect, event) {
      // console.log(currentSelect);
      // console.log(event);
      // },
      /**
       * 日历初次渲染完成后触发事件，如设置事件标记
       */
      afterCalendarRender() {
        const data = [];
        // 异步请求
        setTimeout(() => {
          setTodoLabels({
            pos: 'bottom',
            dotColor: '#40',
            days: data,
          });
          disableDay(1);
        }, 1000);
      },
    });

    that.getPunchRecords(that.data.userInfo.id);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let user = wx.getStorageSync("user");
    if (!user) {
      return;
    }
    return {
      title: user.user_name + "邀请您加入圈子",
      path: "/pages/communityIndex/communityIndex?inviterId=" + user.id + 'inviterName=' + user.user_name,
      success(res) {
        console.log("转发成功");
      }
    }
  },
  getPunchTimeByUserId(userId) {
    api.WxRequest(api.getPunchTimeByUserId, {
      userId: userId
    }, (res) => {
      if (res.status) return;
      that.setData({
        punchTimes: res.data
      })
    });
  },
  navigateBack() {
    wx.navigateBack({
      delta: 1,
    })
  },
  getPunchRecordByDay(day, userId) {
    api.WxRequest(api.getPunchRecordByDay, {
      date: day,
      userId: userId
    }, res => {
      if (res.status) return;
      that.setData({
        punchRecords: res.data
      });
    });
  },
  getPunchRecords(userId) {
    api.WxRequest(api.getPunchRecords, {
      userId: userId
    }, function(res) {
      if (!res.data.length) return;
      if (res.data.length > 7) {
        res.data = res.data.slice(res.data.length - 7);
      }
      let xs = res.data.map(item => {
        return item.created_time;
      });
      let ys = res.data.map(item => {
        return item.weight;
      });
      xs = xs.reverse();
      ys = ys.reverse();
      that.setData({
        punchData: res.data
      });
      that.initChart(xs, ys);
    });
  },
  initChart(xs, ys) {
    // app.deviceInfo.then(function (deviceInfo) {
    //   console.log('设备信息', deviceInfo)
    //   let labels = ["11-01", "11-02", "11-03", "11-04", "11-05", "11-06", "十二月"]
    //   let data = [1, 12, 123, 1234, 12345, 123456, 123456789]
    //   let width = Math.floor(deviceInfo.windowWidth - (deviceInfo.windowWidth / 750) * 10 * 2)//canvas宽度
    //   let height = Math.floor(width / 1.6)//这个项目canvas的width/height为1.6
    //   let canvasId = 'lineCanvas'
    //   let canvasConfig = {
    //     width: width,
    //     height: height,
    //     id: canvasId
    //   }
    //   let config = getConfig(canvasConfig, labels, data)
    //   chartWrap.bind(that)(config)
    // })
    new wxCharts({
      canvasId: 'lineCanvas',
      type: 'area',
      categories: xs,
      series: [{
        name: '日期',
        data: ys,
        format: function(val) {
          return val.toFixed(0);
        }
      }],
      yAxis: {
        title: 'kg',
        format: function(val) {
          return val.toFixed(0);
        },
        min: 30
      },
      width: 320,
      height: 280
    });
  },
  displayFoodSelectList(e) {
    let isshow = e.currentTarget.dataset.isshow;
    // to hide
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    this.animation = animation
    if (isshow) {
      // to hide
      animation.height(0).step();
      this.setData({
        animationFoot: animation.export(),
        isshow: false
      })
    } else {
      // to show
      animation.height(435).step();
      this.setData({
        animationFoot: animation.export(),
        isshow: true
      })
    }
  },
  
});